from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from apps.accounts.decorators import role_required
from apps.common.mixins import RoleRequiredMixin
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from .models import Project
from .forms import ProjectForm, ProjectSearchForm, SubProjectDetailSearchForm


@login_required
def project_list(request):
    """项目列表视图"""
    form = ProjectSearchForm(request.GET)
    projects = Project.objects.all().order_by('-created_at')
    
    # 搜索过滤
    if form.is_valid():
        search = form.cleaned_data.get('search')
        semester = form.cleaned_data.get('semester')
        
        if search:
            projects = projects.filter(
                Q(name__icontains=search) | Q(description__icontains=search)
            )
        
        if semester:
            projects = projects.filter(semester__icontains=semester)
    
    # 分页
    paginator = Paginator(projects, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'form': form,
        'page_obj': page_obj,
        'projects': page_obj,
    }
    return render(request, 'projects/project_list.html', context)


@login_required
def project_detail(request, pk):
    """项目详情视图"""
    project = get_object_or_404(Project, pk=pk)
    
    # 创建子项目搜索表单
    search_form = SubProjectDetailSearchForm(request.GET)
    
    # 获取项目的子项目
    subprojects = project.subproject_set.all().order_by('-created_at')
    
    # 搜索过滤
    if search_form.is_valid():
        search = search_form.cleaned_data.get('search')
        college = search_form.cleaned_data.get('college')
        manager = search_form.cleaned_data.get('manager')
        
        if search:
            subprojects = subprojects.filter(
                Q(name__icontains=search) | Q(description__icontains=search)
            )
        
        if college:
            subprojects = subprojects.filter(college=college)
        
        if manager:
            subprojects = subprojects.filter(
                Q(manager__icontains=manager)
            )
    
    context = {
        'project': project,
        'subprojects': subprojects,
        'search_form': search_form,
    }
    return render(request, 'projects/project_detail.html', context)


@login_required
def project_create(request):
    """创建项目视图"""
    if request.method == 'POST':
        form = ProjectForm(request.POST, user=request.user)
        if form.is_valid():
            project = form.save(commit=False)
            project.created_by = request.user
            project.save()
            messages.success(request, f'项目 "{project.name}" 创建成功！')
            return redirect('projects:project_detail', pk=project.pk)
    else:
        form = ProjectForm(user=request.user)
    
    context = {
        'form': form,
        'title': '创建新项目',
    }
    return render(request, 'projects/project_form.html', context)


@login_required
def project_edit(request, pk):
    """编辑项目视图"""
    project = get_object_or_404(Project, pk=pk)
    
    if request.method == 'POST':
        form = ProjectForm(request.POST, instance=project, user=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, f'项目 "{project.name}" 更新成功！')
            return redirect('projects:project_detail', pk=project.pk)
    else:
        form = ProjectForm(instance=project, user=request.user)
    
    context = {
        'form': form,
        'project': project,
        'title': f'编辑项目: {project.name}',
    }
    return render(request, 'projects/project_form.html', context)


@login_required
@require_POST
def project_delete(request, pk):
    """删除项目视图"""
    project = get_object_or_404(Project, pk=pk)
    
    project_name = project.name
    project.delete()
    
    return JsonResponse({
        'success': True, 
        'message': f'项目 "{project_name}" 已删除'
    })


